package com.example.voicealarm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

import java.util.List;

public class AlarmReceiver extends BroadcastReceiver {
    private static final String TAG = "AlarmReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "Alarm received");
        Alarm alarm = null;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            alarm = intent.getParcelableExtra("alarm", Alarm.class);
        } else {
            alarm = intent.getParcelableExtra("alarm");
        }

        if (alarm == null) {
            Log.e(TAG, "No alarm data received");
            return;
        }

        // Start the RingActivity with flags to ensure it shows even when device is locked
        Intent ringIntent = new Intent(context, RingActivity.class)
            .putExtra("alarm", alarm)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            .addFlags(Intent.FLAG_ACTIVITY_TURN_SCREEN_ON)
//            .addFlags(Intent.FLAG_ACTIVITY_SHOW_WHEN_LOCKED);

        context.startActivity(ringIntent);

        // If this is a repeating alarm, ensure the next occurrence is scheduled
        if (isRepeating(alarm)) {
            Intent serviceIntent = new Intent(context, AlarmService.class)
                .setAction("SCHEDULE_ALARM")
                .putExtra("alarm", alarm);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(serviceIntent);
            } else {
                context.startService(serviceIntent);
            }
        }
    }

    private boolean isRepeating(Alarm alarm) {
        for (boolean day : alarm.activeDays) {
            if (day) return true;
        }
        return false;
    }

    private void rescheduleAlarms(Context context) {
        AlarmPreferences preferences = new AlarmPreferences(context);
        List<Alarm> alarms = preferences.loadAlarms();

        Intent serviceIntent = new Intent(context, AlarmService.class);
        serviceIntent.setAction("SCHEDULE_ALARM");

        for (Alarm alarm : alarms) {
            serviceIntent.putExtra("alarm", alarm);
            context.startService(serviceIntent);
        }
    }
}